#include "Mesh.h"

Mesh::Mesh()
: VBO(0), VBOCount(0),
IBO(0), IBOCount(0)
{
	m_filePath = NULL;
	m_fileName = NULL;
	m_fileConfig = NULL;
}

Mesh::Mesh(char* path, char* name)
: VBO(0), VBOCount(0),
IBO(0), IBOCount(0)
{

	m_filePath = new char[strlen(path)+1];
	strcpy(m_filePath, path);
	m_fileName = new char[strlen(name) + 1];
	strcpy(m_fileName, name);
}

Mesh::~Mesh()
{
	SAFE_DEL_ARRAY(m_filePath);
	SAFE_DEL_ARRAY(m_fileName);
	SAFE_DEL_ARRAY(m_fileConfig);
}

FWint Mesh::LoadData(FWuint vcount, Vertex* vertices, FWuint icount, FWushort* indices)
{
	//Init data
	//Load vertices
	VBOCount = vcount;
	glGenBuffers(1, &VBO);
	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex)*VBOCount, vertices, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	//Load indices
	IBOCount = icount;
	glGenBuffers(1, &IBO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(FWushort)* IBOCount, indices, GL_STATIC_DRAW);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

	return FW_SUCCESS;
}

FWint Mesh::Init()
{
	if (m_fileName == NULL)
		return FW_ERR_NO_DATA;

	std::string file = BASE_SRC_PATH + std::string(m_filePath) + std::string(m_fileName);

	//Load file data
	FILE *f = fopen(file.c_str(), "rb");
	if (!f)
	{
		LOGE("File %s isn't exists.\n", file.c_str());
		return FW_ERR_OPEN;
	}

	//Load data from file
	Vertex* vertices;
	FWuint vertexCount;
	FWushort* indices;
	FWuint indexCount;
	fscanf(f, NUM_STRING, &vertexCount);
	TextModel helper = TextModel();
	vertices = helper.ReadVertices(f, vertexCount);
	fscanf(f, NUM_STRING, &indexCount);
	indices = helper.ReadIndices(f, indexCount);
	fclose(f);

	//Binding vertex data
	LoadData(vertexCount, vertices, indexCount * 3, indices);

	//Release temp buffer data
	SAFE_DEL_ARRAY(vertices);
	SAFE_DEL_ARRAY(indices);

	return FW_SUCCESS;
}

void Mesh::Destroy()
{
	glDeleteBuffers(1, &VBO);
	glDeleteBuffers(1, &IBO);

	SAFE_DEL_ARRAY(m_filePath);
	SAFE_DEL_ARRAY(m_fileName);
	SAFE_DEL_ARRAY(m_fileConfig);
}